# encoding: utf-8
"""
@author: youfeng
@file: response_wrap.py
@time: 2018/9/16 下午2:29
"""
import json

from flask import Response


class ResponseWrap(object):
    HTTP_OK = 200
    HTTP_BAD_REQUEST = 400
    HTTP_UNAUTHORIZED = 401
    HTTP_FORBIDDEN = 403
    HTTP_NOT_FOUND = 404
    HTTP_SERVER_ERROR = 500
    HTTP_NOT_IMPLEMENTED = 501
    HTTP_IP_NOT_ALLOW = 503

    ERROR_MSG = {
        HTTP_OK: 'OK',
        HTTP_BAD_REQUEST: 'bad request',
        HTTP_UNAUTHORIZED: 'unauthorized',
        HTTP_FORBIDDEN: 'forbidden',
        HTTP_NOT_FOUND: 'not found',
        HTTP_SERVER_ERROR: 'server error',
        HTTP_NOT_IMPLEMENTED: 'not implemented',
        HTTP_IP_NOT_ALLOW: "IP not allow",
    }

    # 返回成功
    @staticmethod
    def success(result, **kwargs):
        resp = {
            'success': True,
            'error': None,
            'result': result
        }
        if kwargs:
            resp.update(kwargs)
        data = json.dumps(resp)
        return ResponseWrap.json_resp(data, ResponseWrap.HTTP_OK)

    # 返回失败
    @staticmethod
    def fail(http_status, error=None, result=None):
        resp = {
            'success': False,
            'error': error or ResponseWrap.ERROR_MSG.get(http_status, "undefined error"),
            'result': result
        }
        data = json.dumps(resp)
        return ResponseWrap.json_resp(data, http_status)

    @staticmethod
    def json_resp(data, http_status):
        return Response(data, status=http_status, mimetype="application/json")
